<?php

use app\modules\Admin\models\rankinglistModel;
use Illuminate\Database\Capsule\Manager as DB;

#[用户销售直推业绩统计]
class RankinglistController extends AcommonController
{
    public function init() {
        $this->model = new rankinglistModel();
        $this->table = 'ranking_list';
        $this->primaryKey = 'id';
        parent::init();
    }

    #[统计列表]
    public function indexAction($returnData = FALSE)
    {
        if($this->isPost()){
            $post_data = $this->postData;
            $search_data = [];
            $modeArray = [
                'today',
                'thisweek',
                'yesterday',
                'lastweek',
                'thismonth',
                'lastmonth'
            ];
            $this->model = rankinglistModel::query()->with([
                'member' =>function ($withQuery){
                    $withQuery->select(['id', 'phone', 'nickname', 'realname', 'avatar', 'status']);
                },
                'agent'=>function($withQuery){
                    $withQuery->select('id', 'level');
                },
                'gudong',
                'tuike'=>function($withQuery){
                    $withQuery->with('tuike_level')->select('tuike_id', 'level');
                },
                'qudai'=>function($withQuery){
                    $withQuery->with('qudai_level')->select('qudai_id', 'area_level', 'area', 'area_name');
                }
            ]);
            if(!isset($post_data['mode']) || !in_array($post_data['mode'], $modeArray)){
                $post_data['mode'] = $modeArray[0];
            }
            array_push($search_data, ['mode', '=', $post_data['mode']]);
            if(isset($post_data['agent_level']) && is_numeric($post_data['agent_level']) && $post_data['agent_level'] > 0){
                $this->model = $this->model->whereHas('agent', function ($hasWhere) use($post_data){
                    $hasWhere->where('member.level', $post_data['agent_level']);
                });
            }
            if(isset($post_data['gudong_level']) && is_numeric($post_data['gudong_level']) && $post_data['gudong_level'] > 0){
                $this->model = $this->model->whereHas('gudong')->whereHas('member', function ($hasWhere) use($post_data){
                    $hasWhere->where('member.level', $post_data['gudong_level']);
                });
            }
            if(isset($post_data['tuike_level']) && is_numeric($post_data['tuike_level']) && $post_data['tuike_level'] > 0){
                $this->model = $this->model->whereHas('tuike', function ($hasWhere) use($post_data){
                    $hasWhere->where('tuike.level', $post_data['tuike_level']);
                });
            }
            if(isset($post_data['qudai_level']) && is_numeric($post_data['qudai_level']) && $post_data['qudai_level'] > 0){
                $this->model = $this->model->whereHas('qudai', function ($hasWhere) use($post_data){
                    $hasWhere->where('qudai.area_level', $post_data['qudai_level']);
                });
            }
            $this->search = $search_data;
            return parent::indexAction($returnData); // TODO: Change the autogenerated stub
        }else{
            $this->_view->assign('mode_list', json_encode([
                'today' => '今天',
                'yesterday' => '昨天',
                'thisweek' => '本周',
                'lastweek' => '上周',
                'thismonth' => '本月',
                'lastmonth' => '上月'
            ]));
            $agent_level = agentlevelModel::query()->pluck('name','level');
            if($agent_level){
                $agent_level = $agent_level->toArray();
            }
            $agent_level[0] = '不限';
            $this->_view->assign('agent_level_list', json_encode($agent_level));
            $tuike_level = tuikelevelModel::query()->pluck('name', 'level');
            if($tuike_level){
                $tuike_level = $tuike_level->toArray();
            }
            $tuike_level[0] = '不限';
            $this->_view->assign('tuike_level_list', json_encode($tuike_level));
            $qudai_level = qudailevelModel::query()->pluck('name', 'level');
            if($qudai_level){
                $qudai_level = $qudai_level->toArray();
            }
            $qudai_level[0] = '不限';
            $this->_view->assign('qudai_level_list', json_encode($qudai_level));
            return parent::indexAction($returnData); // TODO: Change the autogenerated stub
        }

    }

    #[销售业绩订单列表]
    public function orderlistAction()
    {
        $id = $this->get('id',0);
        if($this->isPost()){
            $start_on     = $this->get('start_on', '');
            $end_on       = $this->get('end_on', '');
            $keywordsType = $this->get('keywordsType', '');
            $keywords     = $this->get('keywords', '');
            $page = $this->get('page', 1);
            $limit = $this->get('rows', 10);
            $order_ids = rankinglistModel::query()->where('id', $id)->value('order_ids');
            $res = [
                'total' => 0,
                'rows' => [],
                'order' => $order_ids,
            ];
            if(!empty($order_ids)){
                $query = (new \orderModel)->withTrashed()->with('member')->whereIn('id', explode(',',$order_ids));
                $res['total'] = $query->count('id');
                if($res['total']){
                    if (!empty($start_on)) {
                        $query = $query->whereDate('created_at', '>=', $start_on);
                    }
                    if (!empty($end_on)) {
                        $query = $query->whereDate('created_at', '<=', $end_on);
                    }
                    if ($keywords !== '') {
                        switch ($keywordsType) {
                            case 'order_id':
                                $query = $query->where('id', $keywords);
                                break;
                            case 'order_sn':
                                $query = $query->where('order_sn', 'like', "%{$keywords}%");
                                break;
                            case 'consignee':
                                $query = $query->where('consignee', $keywords);
                                break;
                            case 'consignee_phone':
                                $query = $query->where('phone', 'like', "%{$keywords}%");
                                break;
                        }
                    }
                    if (!empty($page)) {
                        $offset = ($page - 1) * $limit;
                        $query  = $query->offset($offset)->limit($limit);
                    }
                    $orders = $query->orderByDesc('created_at')->select(['*'])->get()->append('status_name');
                    if($orders){
                        $res['rows'] = $orders->toArray();
                    }
                    unset($orders);
                }
                unset($query);
            }
            unset($id, $order_ids);
            json($res);
        }else{
            $this->_view->assign('id', $id);
            $this->_view->display( strtolower($this->controller) . '/orderlist.html');
        }
    }

    #[销售业绩订单列表导出]
    public function orderlistexportAction()
    {
        $id     = $this->get('id');
        $keywordsType = $this->get('keywordsType');
        $keywords = $this->get('keywords');
        $start_on = $this->get('start_on');
        $end_on = $this->get('end_on');
        $row = rankinglistModel::query()->find($id);
        if($row){
            $dirpath = APP_PATH . '/public/excel/';
            if ($dirpath !== '.' && !file_exists($dirpath)) {
                mkdir($dirpath, 0777, true);
            }
            $filename = "Ranking_Member{$row->member_id}_{$row->mode}_SalesOrderList" . date('Ymd') . uniqid() . '.xlsx';
            $filepath = $dirpath . $filename;
            $res = exec("php ". APP_PATH . "/public/cli.php export/rankingmemberorderlist \"id={$id}&type={$keywordsType}&keywords={$keywords}&start_on={$start_on}&end_on={$end_on}&path={$filepath}\"");
            if ($res === 'Done' && file_exists($dirpath . $filename)) {
                if( $webpath = syncFile($filepath) ){
                    ret(0, '销售业绩订单列表导出excel成功', $webpath);
                }
            }
        }
        unset($row);
        ret(30003, '销售业绩订单列表导出失败');
    }

    #[销售业绩统计列表导出]
    public function exportAction()
    {
        $qudaiLevel     = $this->get('qudai_level');
        $tuikeLevel = $this->get('tuike_level');
        $gudongLevel = $this->get('gudong_level');
        $agentLevel = $this->get('agent_level');
        $mode = $this->get('mode');

        $dirpath = APP_PATH . '/public/excel/';
        if ($dirpath !== '.' && !file_exists($dirpath)) {
            mkdir($dirpath, 0777, true);
        }
        $filename = 'SalesPerformanceStatistics' . date('Ymd') . uniqid() . '.xlsx';
        $filepath = $dirpath . $filename;
        $res = exec("php ". APP_PATH . "/public/cli.php export/rankinglist \"mode={$mode}&qudai={$qudaiLevel}&tuike={$tuikeLevel}&gudong={$gudongLevel}&agent={$agentLevel}&path={$filepath}\"");
        if ($res === 'Done' && file_exists($dirpath . $filename)) {
            if( $webpath = syncFile($filepath) ){
                ret(0, '销售业绩统计导出excel成功', $webpath);
            }
        }
        ret(30003, '销售业绩统计明细导出失败');
    }
}